package com.hlf.common.aspect;

import com.hlf.common.constants.Constants;
import com.hlf.common.exception.BusinessException;
import com.hlf.modules.merchant.store.entity.Store;
import com.hlf.modules.merchant.store.mapper.StoreMapper;
import com.hlf.modules.merchant.store.service.StoreService;
import com.hlf.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Administrator on 2017/10/31.
 */
@Aspect
@Component
@Order(2)
public class StoreSoftAspect {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreService storeService;
    @Pointcut("execution(public * com.hlf.modules.api.controller.ApiQueue*.*(..)) || execution" +
            "(public * com.hlf.modules.api.controller.ApiTableController.tableListForOrder(..))")
    public void verify() {}

    @Before("verify()")
    public void doVerify() {
        SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
//        String storeId = userEntity.getCurrentStoreId();
        String storeId = "92983473312243712";
        Store store = storeService.queryObject(Long.parseLong(storeId));
        Byte softwareStatus = store.getSoftwareStatus();
        Date expiryDate = store.getExpiryDate();

        if (expiryDate == null){
            throw new BusinessException("请购买软件后使用!");
        }else if (expiryDate.before(new Date())){
            if (Constants.SOFTWARE_PAY_STATUS_TRY_EXPIRE.equals(softwareStatus)){
                throw new BusinessException("试用期结束,请购买后使用!");
            }else if (Constants.SOFTWARE_PAY_STATUS_PAY.equals(softwareStatus)){
                store.setSoftwareStatus(Constants.SOFTWARE_PAY_STATUS_TRY_EXPIRE);
                storeService.update(store);
                throw new BusinessException("软件试用期到期!");
            }else if (Constants.SOFTWARE_PAY_STATUS_PAY_EXPIRE.equals(softwareStatus)){
                throw new BusinessException("软件服务期到期,请续费后继续使用!");
            }else if (Constants.SOFTWARE_PAY_STATUS_PAY.equals(softwareStatus)){
                store.setSoftwareStatus(Constants.SOFTWARE_PAY_STATUS_PAY_EXPIRE);
                storeService.update(store);
                throw new BusinessException("软件服务期到期!");
            }else {
                throw new BusinessException("请购买软件后使用!");
            }
        }else if (!(Constants.SOFTWARE_PAY_STATUS_TRY.equals(softwareStatus)||Constants.SOFTWARE_PAY_STATUS_PAY.equals
                (softwareStatus))){
            throw new BusinessException("请购买软件后使用!");
        }

    }



}
